// import WebSocket, { WebSocketServer } from 'ws';
// const ws = require('ws')

// const wss = new ws.WebSocketServer({ port: 9527 });

// wss.on('connection', function connection(ws) {
//     ws.on('open', function open() {
//         console.log('connected');
//         ws.send('hello');
//       });
      
//   ws.on('message', function message(data, isBinary) {
//     console.log(data)
//     wss.clients.forEach(function each(client) {
//       if (client.readyState === wss.WebSocket.OPEN) {
//         client.send(data);
//       }
//     });
//   });
  
//   ws.on('close', function close() {
//     console.log('disconnected');
//   });
// });
const WebSocket = require('ws')
const ws = new WebSocket.Server({ port: 9527 })

let clients = {}
let clientName = 0

ws.on('connection', (client) => {

  client.name = ++clientName
  clients[client.name] = client

  client.on('message', (msg) => {
    console.log(msg)
    broadcast(client, msg)
  })

  client.on('close', () => {
    delete clients[client.name]
    console.log(client.name + ' 离开了~')
  })
})

function broadcast(client, msg) {
  for (var key in clients) {
    clients[key].send(client.name + ' 说：' + msg)
  }
}